const Koa = require('koa');
const bodyParser = require('koa-bodyparser');
const onerror = require('koa-onerror');
const serve = require('koa-static');
const path = require('path');
const router = require('koa-router')();
const setupRouter = require('./router');

// 导入核心组件
const DataStorage = require('../dataStorage');
const ProjectManager = require('../projectManager');

const MAX_AGE = 1000 * 60 * 5;

module.exports = (server, options) => {
  console.log('[Switcher3] 初始化 UI 服务器');
  
  // 初始化核心组件
  const dataStorage = new DataStorage(options.storage);
  const projectManager = new ProjectManager(dataStorage);
  
  // 初始化组件
  projectManager.init();
  
  console.log('[Switcher3] 核心组件初始化完成');
  
  const app = new Koa();
  app.proxy = true;
  app.silent = true;
  onerror(app);
  
  // 设置路由，传入 projectManager
  setupRouter(router, projectManager);
  
  app.use(bodyParser());
  app.use(router.routes());
  app.use(router.allowedMethods());
  app.use(serve(path.join(__dirname, '../../public'), { maxage: MAX_AGE }));
  
  server.on('request', app.callback());
  
  console.log('[Switcher3] UI 服务器启动完成');
};
